package com.duobab.springbootredisdemo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RedisUtils {
    private static final String LOCK_PREFIX = "redis_lock";
    private static final int LOCK_EXPIRE = 10000;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Set<String> keys() {
        return redisTemplate.keys("*");
    }

    public void setKV(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void delKey(String key) {
        redisTemplate.delete(key);
    }

    public boolean lock(String key) {
        String lockKey = LOCK_PREFIX + key;
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lockKey.getBytes(), String.valueOf(expireAt).getBytes());
            if (acquire) {
                return true;
            }
            return false;
        });
    }

    public void unLock(String key) {
        String lockKey = LOCK_PREFIX + key;
        redisTemplate.delete(lockKey);
    }

}
